package com.yuanqi.controller;

import com.yuanqi.domain.AccountsReceivable;
import com.yuanqi.repository.AccountsReceivableRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.List;

@RestController
@RequestMapping("/api/finance/accounts-receivable")
@CrossOrigin(origins = "*")
public class AccountsReceivableController {
    
    @Autowired
    private AccountsReceivableRepository accountsReceivableRepository;
    
    @GetMapping
    public ResponseEntity<List<AccountsReceivable>> getAllAccountsReceivable() {
        List<AccountsReceivable> accountsReceivable = accountsReceivableRepository.findAll();
        return ResponseEntity.ok(accountsReceivable);
    }
    
    @GetMapping("/{id}")
    public ResponseEntity<AccountsReceivable> getAccountsReceivableById(@PathVariable Long id) {
        return accountsReceivableRepository.findById(id)
                .map(ResponseEntity::ok)
                .orElse(ResponseEntity.notFound().build());
    }
    
    @GetMapping("/customer/{customerId}")
    public ResponseEntity<List<AccountsReceivable>> getAccountsReceivableByCustomer(@PathVariable Long customerId) {
        List<AccountsReceivable> accountsReceivable = accountsReceivableRepository.findByCustomerId(customerId);
        return ResponseEntity.ok(accountsReceivable);
    }
    
    @GetMapping("/overdue")
    public ResponseEntity<List<AccountsReceivable>> getOverdueAccountsReceivable() {
        List<AccountsReceivable> overdueAccounts = accountsReceivableRepository.findByOverdueStatus(1);
        return ResponseEntity.ok(overdueAccounts);
    }
    
    @PostMapping
    public ResponseEntity<AccountsReceivable> createAccountsReceivable(@RequestBody AccountsReceivable accountsReceivable) {
        accountsReceivable.setCreateTime(LocalDateTime.now());
        AccountsReceivable saved = accountsReceivableRepository.save(accountsReceivable);
        return ResponseEntity.ok(saved);
    }
    
    @PutMapping("/{id}")
    public ResponseEntity<AccountsReceivable> updateAccountsReceivable(@PathVariable Long id, @RequestBody AccountsReceivable accountsReceivableDetails) {
                        return accountsReceivableRepository.findById(id)
                .map(existing -> {
                    existing.setCustomerId(accountsReceivableDetails.getCustomerId());
                    existing.setOrderId(accountsReceivableDetails.getOrderId());
                    existing.setInvoiceAmount(accountsReceivableDetails.getInvoiceAmount());
                    existing.setReceivedAmount(accountsReceivableDetails.getReceivedAmount());
                    existing.setOutstandingAmount(accountsReceivableDetails.getOutstandingAmount());
                    existing.setDueDate(accountsReceivableDetails.getDueDate());
                    existing.setOverdueStatus(accountsReceivableDetails.getOverdueStatus());
                    
                    // 检查是否逾期
                    if (LocalDate.now().isAfter(existing.getDueDate()) && existing.getOutstandingAmount().doubleValue() > 0) {
                        existing.setOverdueStatus(1);
                    } else {
                        existing.setOverdueStatus(0);
                    }
                    
                    return ResponseEntity.ok(accountsReceivableRepository.save(existing));
                })
                .orElse(ResponseEntity.notFound().build());
    }
    
    @DeleteMapping("/{id}")
    public ResponseEntity<Void> deleteAccountsReceivable(@PathVariable Long id) {
        if (accountsReceivableRepository.existsById(id)) {
            accountsReceivableRepository.deleteById(id);
            return ResponseEntity.ok().build();
        }
        return ResponseEntity.notFound().build();
    }
    
    @GetMapping("/stats/total-overdue")
    public ResponseEntity<Double> getTotalOverdueAmount() {
        Double totalOverdue = accountsReceivableRepository.getTotalOverdueAmount();
        return ResponseEntity.ok(totalOverdue != null ? totalOverdue : 0.0);
    }
    
    @GetMapping("/stats/total-outstanding")
    public ResponseEntity<Double> getTotalOutstandingAmount() {
        Double totalOutstanding = accountsReceivableRepository.getTotalOutstandingAmount();
        return ResponseEntity.ok(totalOutstanding != null ? totalOutstanding : 0.0);
    }
}


